package com.atwu.wl2022.controller;

import com.atwu.wl2022.entity.*;
import com.atwu.wl2022.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 只有登录了，并且是管理员才能访问
 *
 * @author wulejay
 */
@Controller
@RequestMapping("/root")
@Slf4j
public class RootController {

	@Autowired
	IArticleService iArticleService;
	@Autowired
	IUserService iUserService;
	@Autowired
	ILinkService iLinkService;
	@Autowired
	IDiaryService iDiaryService;
	@Autowired
	ICommentService iCommentService;
	@Autowired
	ITypeService iTypeService;

	/**
	 * 去后台首页
	 *
	 * @return 地址
	 */
	@GetMapping("/index")
	public String rootIndex(HttpServletRequest request, @RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
		//获取文章总数
		Integer articleCount = iArticleService.count();
		//获取用户总数
		Integer userCount = iUserService.count();
		//获取留言数
		Integer messageCount = iCommentService.count(new QueryWrapper<Comment>().eq("article_id", 0).isNull("pid"));
		//获取友链数
		Integer linkCount = iLinkService.count();
		//获取文章信息封装分页
		List<Article> list = iArticleService.list();
		model.addAttribute("users", list);
		//分页查询数据
		Page<Article> articlePage = new Page<>(pn, 5);
		Page<Article> page = iArticleService.page(articlePage);
		//将类型信息封装存进request域中
		List<Type> categoryNavigation = iTypeService.list();
		request.setAttribute("categoryNavigation", categoryNavigation);
		//当前页
		long current = page.getCurrent();
		System.out.println(current);
		//总页数
//		long pages = page.getPages();
		//总记录数
//		long total = page.getTotal();
		//数据集合
//		List<Article> records = page.getRecords();

		request.setAttribute("articleCount", articleCount);
		request.setAttribute("userCount", userCount);
		request.setAttribute("messageCount", messageCount);
		request.setAttribute("linkCount", linkCount);
		model.addAttribute("page", page);
		return "root/index";
	}

	/**
	 * 去添加文章页面
	 *
	 * @return 地址
	 */
	@GetMapping("/addArticle")
	public String addArticle(HttpServletRequest request) {
		//将类型信息封装存进request域中
		List<Type> categoryNavigation = iTypeService.list();
		request.setAttribute("categoryNavigation", categoryNavigation);
		return "root/addArticle";
	}

	/**
	 * 去添加日志页面
	 *
	 * @return 地址
	 */
	@GetMapping("/toAddLog")
	public String toAddLog() {
		return "root/addLog";
	}

	/**
	 * 实现增加日志的逻辑
	 */
	@PostMapping("/addLog")
	@ResponseBody
	public boolean addLog(@RequestParam("time") Date time, @RequestParam("diary") String diary) {
		log.info("在{}，添加的日志内容为：{}", time, diary);
		return iDiaryService.save(new Diary(null, time, diary));
	}

	/**
	 * 去添加友链页面
	 *
	 * @return 地址
	 */
	@GetMapping("/toAddFriendsChain")
	public String toAddFriendsChain() {
		return "root/addFriendsChain";
	}

	/**
	 * 实现添加友链的具体逻辑
	 */
	@PostMapping("/addFriendsChain")
	@ResponseBody
	public boolean addFriendsChain(@RequestParam("time") Date time,
	                               @RequestParam("webUrl") String webUrl,
	                               @RequestParam("webIcon") String webIcon,
	                               @RequestParam("webName") String webName,
	                               @RequestParam("summary") String summary) {
		return iLinkService.save(new Link(null, webUrl, webIcon, webName, summary, time));
	}

	/**
	 * 去修改文章页面
	 *
	 * @return 地址
	 */
	@GetMapping("/toModifyArticles/{articleId}")
	public String toModifyArticles(@PathVariable(name = "articleId") Integer articleId, HttpServletRequest request) {
		log.info("要修改的文章id为：{}", articleId);
		Article byId = iArticleService.getById(articleId);
		request.setAttribute("editArticle", byId);
		//将类型信息封装存进request域中
		List<Type> categoryNavigation = iTypeService.list();
		request.setAttribute("categoryNavigation", categoryNavigation);
		return "root/modifyArticles";
	}

	/**
	 * 修改文章功能
	 *
	 * @return 结果
	 */
	@PostMapping("/modifyArticles")
	@ResponseBody
	public boolean modifyArticles(@RequestParam("id") String id,
	                              @RequestParam("createBy") String createBy,
	                              @RequestParam("summary") String summary,
	                              @RequestParam("articleType") Integer articleType,
	                              @RequestParam("quoteLinkText") String quoteLinkText,
	                              @RequestParam("editorContentTextarea") String articleContent) {
		//未修改图片
		log.info("{},{},{},{},{}", id, createBy, articleType, quoteLinkText, articleContent);
		return iArticleService.update(new UpdateWrapper<Article>().eq("id", id).set("create_by", createBy).set("summary", summary).set("article_type", articleType).set("quote_link", quoteLinkText).set("article_content", articleContent));
	}

	/**
	 * 修改文章功能2
	 *
	 * @return 结果
	 */
	@PostMapping("/modifyArticlesWithImag")
	@ResponseBody
	public boolean modifyArticlesWithImag(@RequestParam("id") String id,
	                                      @RequestParam("createBy") String createBy,
	                                      @RequestParam("summary") String summary,
	                                      @RequestParam("articleType") Integer articleType,
	                                      @RequestParam("quoteLinkText") String quoteLinkText,
	                                      @RequestParam("editorContentTextarea") String articleContent,
	                                      @RequestPart("headImage") MultipartFile headImage) throws IOException {
		//修改了图片
		//首先判断路径下该图片（id-headImage）是否存在，存在就
		//先判断有没有原来的头像（用户id+图片名）
		//有：删除
		//没有：上传（图片名为用户id+图片名）
		File path = new File(ResourceUtils.getURL("classpath:").getPath());
		if (!path.exists()) {
			path = new File("");
		}
		File upload = new File(path.getAbsolutePath(), "static/image/articleImages");
		if (!upload.exists()) {
			upload.mkdirs();
		}
		String parent = upload.getPath();
		log.info("文章图片上传路径:{}", parent);
		Article image = iArticleService.queryArticleSelectImage(Integer.parseInt(id));
		String s = parent + "\\" + image.getImage();
		log.info("上一个头像文件地址:{}", s);
		File dir = new File(s);
		if (dir.exists()) {
			log.info("图像文件已存在");
			dir.delete();//删除文件
		}
		//上传图片到该地址
		//1、获取接收的图片名
		String filename = headImage.getOriginalFilename();
		//2、新的文件名字，防止存入重名地址
		String newFileName = id + "-" + filename;
		//3、封装上传文件位置的全路径
		File targetFile = new File(parent, newFileName);
		//4、把图片上传到封装上传文件位置的全路径
		headImage.transferTo(targetFile);
		log.info("存入的文章图片名为：{}", newFileName);
		return iArticleService.update(new UpdateWrapper<Article>().eq("id", id).set("create_by", createBy).set("summary", summary).set("article_type", articleType).set("quote_link", quoteLinkText).set("article_content", articleContent).set("image", newFileName));
	}


	/**
	 * 往数据库添加文章信息
	 *
	 * @param title          标题
	 * @param createBy       作者
	 * @param summary        概述
	 * @param articleContent 文章主体
	 * @param image          头图片
	 * @param quoteLinkText  引用链接文本
	 * @param articleType    文章类型
	 * @param quoteLink      引用链接
	 * @return 回到此页面
	 */
	@PostMapping("/add")
	public String addArticle(@RequestParam("title") String title,
	                         @RequestParam("createBy") String createBy,
	                         @RequestParam("summary") String summary,
	                         @RequestParam("articleContent") String articleContent,
	                         @RequestPart("image") MultipartFile image,
	                         @RequestParam("quoteLinkText") String quoteLinkText,
	                         @RequestParam("articleType") Integer articleType,
	                         @RequestParam("quoteLink") String quoteLink) throws FileNotFoundException {
		String imageName;
		String defaultImage = "c7044c1e-61f4-4662-b735-858644c25d20" + ".jpg";
//		获取项目图片目录的路径
//		String currentPath = System.getProperty("user.dir");
//		String filePath = "/" + currentPath + "\\src\\main\\resources\\static\\image\\articleImages\\";
//		log.info("文章图片上传路径：{}",filePath);

		File path = new File(ResourceUtils.getURL("classpath:").getPath());
		if (!path.exists()) {
			path = new File("");
		}
		File upload = new File(path.getAbsolutePath(), "static/image/articleImages");
		if (!upload.exists()) {
			upload.mkdirs();
		}
		String parent = upload.getPath();

		// 保存头像文件的文件夹
		File dir = new File(parent);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		//判断图片是否为空
		if (!image.isEmpty()) {
			//图片信息不为空
			//1、将图片存入项目路径中
			//获取接收的图片名
			String originalFilename = image.getOriginalFilename();
			//封装上传文件位置的全路径
			File targetFile = new File(parent, originalFilename);
			//把本地文件上传到封装上传文件位置的全路径
			try {
				image.transferTo(targetFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			log.info("存入的图片名为：{}", originalFilename);
			imageName = originalFilename;
			log.info("文章图片上传路径：{}", parent);


		} else {
			//图片信息为空
			//1、将默认图像名存入数据库中
			log.info("存入的随机图片名为：{}", defaultImage);
			imageName = defaultImage;
		}
		//判断文章是否为原创
		//1、文章不是原创，引用链接为接收到的quoteLinkText
		if (!"me".equals(quoteLink)) {
			quoteLink = quoteLinkText;
		} else {
			//文章是原创，引用链接空
			quoteLink = "";
		}

		//将文章信息封装，存入数据库中
		Article article = new Article(null, null, null, title, createBy, summary, articleContent, imageName, articleType, 0, 0, 0, quoteLink, 0);
		boolean save = iArticleService.save(article);
		if (!save) {
			File file = new File(parent + "/" + imageName);
			log.info("文章上传失败，删除已上传的指定路径的图片：{}", file);
			//删除存进去的图片
			file.delete();
		}


		//当不是默认图片时，修改图片名字为指定格式,再将路径下已经存好的图片重新命名
		if (!imageName.equals(defaultImage)) {
			Article one = iArticleService.getOne(new QueryWrapper<Article>().eq("image", imageName));
			Integer id = one.getId();
			String headImage = id + "-" + imageName;
			iArticleService.update(new UpdateWrapper<Article>().eq("id", id).set("image", headImage));
			log.info("文章头图片名字为：{}", headImage);
			//将路径下已经存好的图片重新命名
			File file = new File(parent + "/" + imageName);
			File file2 = new File(parent + "/" + headImage);
			file.renameTo(file2);

		}

		log.info("最终存入数据库的信息：title ==> {},createBy ==> {},articleType ==> {},quoteLink ==> {},quoteLinkText={}",
				title, createBy, articleType, quoteLink, quoteLinkText);
		return "redirect:/root/addArticle";
	}
}

